package com.example.a1.activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import com.example.a1.R;
import com.example.a1.adapter.CourseAdapter;
import com.example.a1.model.Course;
import com.example.a1.util.HttpUtil;
import java.util.ArrayList;
import java.util.List;

public class CategoryListActivity extends AppCompatActivity {
    private List<Course> courseList = new ArrayList<>();
    private CourseAdapter adapter;
    private int categoryId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_category_list);

        // 初始化标题栏和列表
        TextView titleTv = findViewById(R.id.category_list_title);
        ListView listView = findViewById(R.id.category_course_list);

        adapter = new CourseAdapter(this, courseList);
        listView.setAdapter(adapter);

        // 获取传递的参数（分类ID+分类名称）
        Intent intent = getIntent();
        categoryId = intent.getIntExtra("category_id", 0);
        String categoryName = intent.getStringExtra("category_name");

        // 标题显示逻辑
        if (categoryName != null) {
            titleTv.setText("分类浏览 - " + categoryName);

            titleTv.setTextSize(android.util.TypedValue.COMPLEX_UNIT_SP, 18);
            titleTv.setTypeface(titleTv.getTypeface(), android.graphics.Typeface.BOLD);
            titleTv.setBackgroundColor(ContextCompat.getColor(this, R.color.white));
            titleTv.setTextColor(ContextCompat.getColor(this, android.R.color.background_dark));
            titleTv.setPadding(16, 16, 16, 16);
        }

        // 加载分类对应的课程
        loadCoursesByCategoryId();

        // 分类课程点击事件
        listView.setOnItemClickListener((parent, view, position, id) -> {
            if (position < courseList.size()) {
                Course course = courseList.get(position);
                Intent courseIntent = new Intent(this, CourseDetailActivity.class);
                courseIntent.putExtra("course_detail_url", course.getDetailUrl());
                startActivity(courseIntent);
            }
        });
    }

    // 加载分类课程数据
    private void loadCoursesByCategoryId() {
        HttpUtil.getCoursesByCategoryId(categoryId, new HttpUtil.OnDataLoadedListener<List<Course>>() {
            @Override
            public void onSuccess(List<Course> data) {
                courseList.clear();
                courseList.addAll(data);
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onFailure(String error) {
                Toast.makeText(CategoryListActivity.this, "课程加载失败: " + error, Toast.LENGTH_SHORT).show();
            }
        });
    }
}